<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 登录</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }
        .login-header {
            text-align: center;
            margin-bottom: 1.5rem;
        }
        .login-header h2 {
            color: #2c3e50;
            font-weight: bold;
        }
        .form-group {
            margin-bottom: 1.2rem;
        }
        .form-control {
            border-radius: 50px;
            padding: 0.75rem 1.25rem;
        }
        .btn-login {
            width: 100%;
            border-radius: 50px;
            padding: 0.75rem;
            font-weight: bold;
            background-color: #2c3e50;
            border-color: #2c3e50;
            transition: all 0.3s ease;
        }
        .btn-login:hover {
            background-color: #34495e;
            border-color: #34495e;
            transform: translateY(-2px);
        }
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
            display: none;
        }
        .form-control.is-invalid {
            border-color: #dc3545;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 1rem;
        }
        .spinner {
            width: 2rem;
            height: 2rem;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: #2c3e50;
            animation: spin 1s ease-in-out infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .library-icon {
            font-size: 3rem;
            color: #2c3e50;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-header">
        <i class="bi bi-book-half library-icon"></i>
        <h2>图书馆管理系统</h2>
        <p>请登录您的账号</p>
    </div>

    <div class="loading">
        <div class="spinner"></div>
        <p class="mt-2">登录中...</p>
    </div>

    <form id="loginForm">
        <div class="form-group">
            <label for="username" class="form-label">用户名</label>
            <div class="input-group">
                    <span class="input-group-text">
                        <i class="bi bi-person"></i>
                    </span>
                <input type="text" class="form-control" id="username" placeholder="请输入用户名" required>
            </div>
            <div class="error-message" id="usernameError">请输入用户名</div>
        </div>

        <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <div class="input-group">
                    <span class="input-group-text">
                        <i class="bi bi-lock"></i>
                    </span>
                <input type="password" class="form-control" id="password" placeholder="请输入密码" required>
                <button type="button" class="btn btn-outline-secondary" id="togglePassword">
                    <i class="bi bi-eye"></i>
                </button>
            </div>
            <div class="error-message" id="passwordError">请输入密码</div>
        </div>

        <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" id="rememberMe">
            <label class="form-check-label" for="rememberMe">记住我</label>
        </div>

        <button type="submit" class="btn btn-primary btn-login">登录</button>

        <div class="error-message mt-3 text-center" id="loginError"></div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 页面加载时检查是否已登录
    document.addEventListener('DOMContentLoaded', function() {
        const token = localStorage.getItem('token');
        if (token) {
            // 已登录，跳转到图书管理页面
            window.location.href = '/books.html';
        }

        // 尝试从localStorage加载记住的用户名
        const savedUsername = localStorage.getItem('savedUsername');
        if (savedUsername) {
            document.getElementById('username').value = savedUsername;
            document.getElementById('rememberMe').checked = true;
        }
    });

    // 密码显示/隐藏切换
    document.getElementById('togglePassword').addEventListener('click', function() {
        const passwordInput = document.getElementById('password');
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);

        // 切换图标
        const icon = this.querySelector('i');
        if (type === 'password') {
            icon.classList.remove('bi-eye-slash');
            icon.classList.add('bi-eye');
        } else {
            icon.classList.remove('bi-eye');
            icon.classList.add('bi-eye-slash');
        }
    });

    // 表单验证
    function validateForm() {
        let isValid = true;
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;

        // 验证用户名
        if (username === '') {
            showError('usernameError', '请输入用户名');
            isValid = false;
        } else {
            hideError('usernameError');
        }

        // 验证密码
        if (password === '') {
            showError('passwordError', '请输入密码');
            isValid = false;
        } else {
            hideError('passwordError');
        }

        // 隐藏登录错误信息
        hideError('loginError');

        return isValid;
    }

    // 显示错误信息
    function showError(elementId, message) {
        const errorElement = document.getElementById(elementId);
        errorElement.textContent = message;
        errorElement.style.display = 'block';

        if (elementId === 'usernameError') {
            document.getElementById('username').classList.add('is-invalid');
        } else if (elementId === 'passwordError') {
            document.getElementById('password').classList.add('is-invalid');
        }
    }

    // 隐藏错误信息
    function hideError(elementId) {
        const errorElement = document.getElementById(elementId);
        errorElement.style.display = 'none';

        if (elementId === 'usernameError') {
            document.getElementById('username').classList.remove('is-invalid');
        } else if (elementId === 'passwordError') {
            document.getElementById('password').classList.remove('is-invalid');
        }
    }

    // 登录表单提交
    document.getElementById('loginForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        // 表单验证
        if (!validateForm()) {
            return;
        }

        // 显示加载状态
        document.querySelector('.loading').style.display = 'block';
        document.getElementById('loginForm').style.display = 'none';

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const rememberMe = document.getElementById('rememberMe').checked;

        try {
            // 发送登录请求
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });

            const data = await response.json();

            // 隐藏加载状态
            document.querySelector('.loading').style.display = 'none';
            document.getElementById('loginForm').style.display = 'block';

            if (response.ok) {
                // 登录成功，保存token和用户信息
                localStorage.setItem('token', data.token);
                localStorage.setItem('user', JSON.stringify(data.user));

                // 如果勾选了记住我，保存用户名
                if (rememberMe) {
                    localStorage.setItem('savedUsername', username);
                } else {
                    localStorage.removeItem('savedUsername');
                }

                // 跳转到图书管理页面
                window.location.href = '/books.html';
            } else {
                // 登录失败，显示错误信息
                showError('loginError', data.message || '登录失败，请检查用户名和密码');
            }
        } catch (error) {
            console.error('登录请求失败:', error);

            // 隐藏加载状态
            document.querySelector('.loading').style.display = 'none';
            document.getElementById('loginForm').style.display = 'block';

            showError('loginError', '服务器连接失败，请稍后重试');
        }
    });

    // 输入框输入时清除错误状态
    document.getElementById('username').addEventListener('input', function() {
        hideError('usernameError');
        hideError('loginError');
    });

    document.getElementById('password').addEventListener('input', function() {
        hideError('passwordError');
        hideError('loginError');
    });
</script>
</body>
</html>
